package com.example.composesideeffects.sample

import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Snackbar
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier

/**
 * @author huangzehui
 * @date 9/6/2024 下午10:20 周日
 * @description
 *
 * LaunchedEffect
 * https://www.bilibili.com/video/BV1ob4y1a7ad?p=79&spm_id_from=pageDriver&vd_source=e07cc8cc94eb22bd76722071b03cd199
 */

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ScaffoldSample(
    state:MutableState<Boolean>,
    snackbarHostState:SnackbarHostState,
) {
//    val snackbarHostState = remember {
//        SnackbarHostState()
//    }

    if (state.value){
        LaunchedEffect(key1 = snackbarHostState) {
            snackbarHostState.showSnackbar(
                message = "Error Message",
                actionLabel = "Retry Message"
            )
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(title = {
                Text(text = "脚手架")
            })
        },
        content = {
            it.calculateBottomPadding()
            Column {

                SnackbarHost(hostState = snackbarHostState) {
                    Snackbar(
                        content = { Text(text = "文本") },
                        action = {
                            Button(onClick = {  state.value = false }) {
                                Text(text = "关闭")
                            }
                        }
                    )
                }

                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Button(onClick = {
                        state.value = !state.value
                    }) {
                        Text(text = "Error occurs")
                    }
                }



            }
        }
    )
}


@SuppressLint("UnrememberedMutableState")
@Composable
fun LaunchEffectSample() {

    val snackbarHostState = remember {
        SnackbarHostState()
    }

    LaunchedEffect(key1 = Unit) {
        snackbarHostState.showSnackbar("Hello")
    }

    ScaffoldSample(state = mutableStateOf(false), snackbarHostState = snackbarHostState)
}